#include "tcp.h"

#include <winsock2.h>  // This must be included before "windows.h"
#include <windows.h>

#include "global.h"
#include "checksum.h"
#include "lists.h"

#include "ip.h"

//
// Translate IPv4 TCP packet to IPv6 TCP packet
//
void tcp4to6( eth_header *eh, ip_header *ih, tcp_header *th )
{
    
    u_short length = sizeof(eth_header) + ntohs(ih->length) + 20;  // Send packet length
	eth_header   *eh_6;
	ip6_header   *ip6h;
	tcp_header   *th_6;

	memset( v4SendBuffer, 0, 1600 );
	eh_6   = (eth_header   *)( v4SendBuffer );
	ip6h   = (ip6_header   *)( v4SendBuffer + sizeof(eth_header) );
	th_6   = (tcp_header   *)( v4SendBuffer + sizeof(eth_header) + sizeof(ip6_header) );
    
    // Build Ethernet header
    int i;
	// Copy dst MAC
	for( i =0; i < 6; i++ )
		eh_6->dmac[i] = eh->dmac[i];
	// Fill src MAC with v6LocalMAC
	for( i =0; i < 6; i++ )
		eh_6->smac[i] = v6LocalMAC[i];
	eh_6->type = htons(ETH_IP6);

    // Build IPv6 header
	ip4to6( ih, ip6h );
    
    // Copy TCP header & data
	int size = ntohs(ih->length) - (ih->ver_ihl & 0x0f) * 4;
	memcpy( th_6, th, size );
    
    // To Do: Port mapping!!!!
    
    checksum_tcp6( ip6h, th_6 );

	// Done

	/* Send down the packet */
	if (pcap_sendpacket(v6Handle, v4SendBuffer, length /* size */) != 0)
	{
		printf("v4 device: Error sending the packet to v6 side: %s\n", pcap_geterr(v6Handle));
	}
    
    return;
}

//
// Translate IPv6 TCP packet to IPv4 TCP packet
//
void tcp6to4( eth_header *eh, ip6_header *ip6h, tcp_header *th )
{
    int length = sizeof(eth_header) + ntohs(ip6h->payload) + 20;  // Send packet length
	eth_header   *eh_4;
	ip_header    *ih;
	tcp_header   *th_4;

	memset( v6SendBuffer, 0, 1600 );
	eh_4   = (eth_header  *)( v6SendBuffer );
	ih     = (ip_header   *)( v6SendBuffer + sizeof(eth_header) );
	th_4   = (tcp_header  *)( v6SendBuffer + sizeof(eth_header) + sizeof(ip_header) );

    // Build Ethernet header
	int i;
	// Fill dst MAC with v4LocalMAC
	for( i =0; i < 6; i++ )
		eh_4->dmac[i] = v4LocalMAC[i];
	// Copy src MAC 
	for( i =0; i < 6; i++ )
		eh_4->smac[i] = eh->smac[i];
	eh_4->type = htons(ETH_IP);

    // Build IPv4 header
	ip6to4( ip6h, ih );
    
    // Copy TCP header & data
    int size = ntohs(ip6h->payload);
    memcpy( th_4, th, size );
    
    // To Do: Port mapping!!!!
    
    checksum_tcp4( ih, th_4 );

	// Done

	/* Send down the packet */
	if (pcap_sendpacket(v4Handle, v6SendBuffer, length /* size */) != 0)
	{
		printf("v6 device: Error sending the packet to v4 side: %s\n", pcap_geterr(v4Handle));
	}

    return;
}
